package com.cy.module;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cy.config.EnumConst;
import com.cy.ext.plugin.route.ControllerBind;
import com.cy.model.License;
import com.cy.model.LicenseLog;
import com.cy.model.LicenseToken;
import com.cy.model.LicenseTokenLog;
import com.cy.model.User;
import com.jfinal.plugin.activerecord.Page;
import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.Map;

@ControllerBind(controllerKey = "/clmp/licenseToken")
public class LicenseTokenController extends WebApiController {
    @Override
    public void index() {
        LicenseToken licenseToken = getModel(LicenseToken.class);
        int page = getParaToInt("pageIndex");
        int pageSize = getParaToInt("limit");
        Page<LicenseToken> licenseTokenPage = LicenseToken.dao.paginate(page, pageSize, LicenseToken.SELECT_ALL, licenseToken);
        renderBuiPage(licenseTokenPage, 200);
    }

    @Override
    public void update() {
        int id = getParaToInt();
        LicenseToken tempLicenseToken = getModel(LicenseToken.class);
        LicenseToken licenseToken = LicenseToken.dao.findById(id);
        licenseToken.cover(tempLicenseToken);

        if (licenseToken.update()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void save() {
        LicenseToken licenseToken = getModel(LicenseToken.class);
        if (licenseToken.save()) {
            renderSuccess();
        } else {
            renderFail();
        }
    }

    @Override
    public void delete() {
        String[] ids = getPara().split("-");
        for (String id : ids) {
            LicenseToken.dao.deleteById(id);
        }
        renderSuccess();
    }

    public void bindOrder(){
        Map<String,String[]> map = getParaMap();
        int count = 0;
        String paramStr = map.get("param")[0];
        JSONArray paramList = JSONArray.parseArray(paramStr);
        for (int i = 0 ; i < paramList.size() ; i++){
            JSONObject bindData = (JSONObject) paramList.get(i);
            int licenseTokenId = bindData.getIntValue("license_token_id");
            String lt = bindData.getString("license_token");
            if (licenseTokenId > 0 && StringUtils.isNotBlank(lt)){
                LicenseToken licenseToken = LicenseToken.dao.findById(licenseTokenId);
                if (null != licenseToken){
                    licenseToken.setLicenseToken(lt).update();
                    count++;
                }else{
                    getLog().warn("订单绑定token:" + lt + "时，找不到license_token记录!");
                }
            }
        }
        if (count == paramList.size() ){
            renderSuccess();
        }else {
            renderFail();
        }
        return ;
    }

    public void getTokenByOrder(){
        JSONObject json = new JSONObject();

        Map<String,String[]> map = getParaMap();
        String tokenId = map.get("id")[0];
        if(StringUtils.isNotEmpty(tokenId)){
            LicenseToken licenseToken = LicenseToken.dao.findById(tokenId);
            if (licenseToken != null){
                String token = licenseToken.getLicenseToken();
                json.put("status",EnumConst.RetCode.SUCCESS.getCode());
                json.put("token",token);
                renderJson(json);
                return;
            }
        }

        json.put("status", EnumConst.RetCode.NODATA.getCode());
        renderJson(json);
    }

    public void checkToken(){
        JSONObject json = new JSONObject();
        Map<String,String[]> map = getParaMap();
        String token = map.get("token")[0];
        boolean isHas = false;
        if(StringUtils.isNotEmpty(token)){
            isHas = LicenseToken.dao.checkTokenUnique(token);

        }
        json.put("status",EnumConst.RetCode.SUCCESS.getCode());
        json.put("isHas",isHas);
        renderJson(json);
    }

    public void fatchLicense(){
        JSONObject json = new JSONObject();
        Map<String,String[]> map = getParaMap();
        User user = getLoginUser();
        String token = null,
         shareCode = null;

        if (null != map.get("t")){
            token = map.get("t")[0];
        }
        if(null != map.get("s_code")){
            shareCode = map.get("s_code")[0];
        }

        if(StringUtils.isBlank(token) ){
            renderStatus(EnumConst.RetCode.PARAMETER_IS_INVALID.getCode());
            return;
        }

        LicenseToken tokenInfo = LicenseToken.dao.findInfoByToken(token);
        if(null != tokenInfo){
            String uMobile = user.getMobile();
            String oPhone = tokenInfo.get("phone");
            //先判断订单对应的用户id相同，或者手机与订单号码相同则可认领，生成log
            if(user.getUserId() == tokenInfo.getLong("order_user_id") || uMobile.equals(oPhone)){
                //认领使用权
                json = claimLicense(tokenInfo);
            }else {
                //如果号码不一致则验证分享码
                if(StringUtils.isBlank(shareCode)){
                    //如果验证码为空则
                    addTokenLog(0,tokenInfo.getTokenId(),tokenInfo.getLicenseToken(),"分享码为空");
                    renderStatus(30030,"分享码为空");
                    return;
                }else{
                    User orderUser = User.dao.findByMobile(oPhone);
                    if (null != orderUser){
                        if (orderUser.getShareCode().equals(shareCode)){
                            //认领使用权
                            json = claimLicense(tokenInfo);

                        }else{
                            addTokenLog(0,tokenInfo.getTokenId(),tokenInfo.getLicenseToken(),"分享码不正确");
                            renderStatus(30031,"分享码不正确");
                            return;
                        }
                    }else{
                        addTokenLog(0,tokenInfo.getTokenId(),tokenInfo.getLicenseToken(),"找不到购买用户");
                        renderStatus(30032,"找不到购买用户，请联系客服");
                        return;
                    }
                }
            }
        }else{
//            addTokenLog(0,null,token,"二维码无效");
            json.put("status",30033);
            json.put("msg", "二维码无效");
        }
        renderJson(json);
    }

    private JSONObject claimLicense(LicenseToken tokenInfo){
        JSONObject json = new JSONObject();
        if(tokenInfo.getStatus() == LicenseToken.Status.ISUSE.getCode()){
            json.put("status",30034);
            json.put("msg","此二维码已领用");
            return json;
        }
        User user = getLoginUser();
        LicenseLog log = new LicenseLog();
        log.setFromObject(0l).setToObject(user.getUserId()).setType(LicenseLog.Type.CREATE.getCode())
                .setNum(tokenInfo.getNum()).setStatus(0).setOperationTime(new Date());
        if(log.save()){
            tokenInfo.setUserId(user.getUserId()).setLicenseLogId(log.getLogId()).setStatus(1);
        }
        if(tokenInfo.update()){
            License license = License.dao.findByUserId(user.getUserId());
            license.fatchLicense(tokenInfo.getNum());
            if (license.update()){
                log.setStatus(1).update();
                addTokenLog(1,tokenInfo.getTokenId(),tokenInfo.getLicenseToken(),"认领成功");
                json.put("status",EnumConst.RetCode.SUCCESS.getCode());
                json.put("license",license.getLicenseAvailable());
                json.put("num",tokenInfo.getNum());
            }
        }else{
            json.put("status",EnumConst.RetCode.SYSTEM_ERROR.getCode());
        }
        return  json;
    }

    private void addTokenLog(int type,Long tokenId ,String tokenCode,String remark){
        LicenseTokenLog licenseTokenLog = new LicenseTokenLog();
        licenseTokenLog.setOperationTime(new Date()).setUserId(getLoginUser().getUserId()).setMobile(getLoginUser().getMobile())
                .setLicenseTokenId(tokenId).setLicenseTokenCode(tokenCode).setType(type).setRemark(remark).save();
    }
}
